﻿//Copyright md bravo - feel free to modify this code in any way - just leave this notice ;)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MongoDB.Bson;

namespace ShareCDN.Engine.Web
{

	public class UploadHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState
	{

		public bool IsReusable
		{
			get { return false; }
		}

		public void ProcessRequest(HttpContext context)
		{
			
			var rq = context.Request;
			if (rq.QueryString["op"] == "complete")
			{
				var fileName = rq.QueryString["file"];
				context.Response.ContentType = "application/json";
				var statusDoc = new BsonDocument();
				var uploadSlot = UploadManager.Current.GetUploadSlotForFile(fileName);
				if (uploadSlot.Status == UploadSlot.UploadStatus.Uploading)
				{
					uploadSlot.FileName = rq["filename"];
					uploadSlot.ForceDownload = rq["forcedownload"] == "true";
					uploadSlot.GenerateRemoveLink = rq["remlink"] == "true";
					uploadSlot.AbsoluteExpiration = GetExpiration(rq["exp"]);
					uploadSlot.StartSaving();
					statusDoc["status"] = "Saving";
				}
				else if (uploadSlot.Status == UploadSlot.UploadStatus.Converting)
				{
					statusDoc["status"] = "Saving";
				}
				else if (uploadSlot.Status == UploadSlot.UploadStatus.Uploaded)
				{
					statusDoc["status"] = "Uploaded";
					statusDoc["hash"] = uploadSlot.Result.SecretKey;
					statusDoc["url"] = UploadManager.Current.GenerateUrlForUploadedFile(uploadSlot);

				}
				else if (uploadSlot.Status == UploadSlot.UploadStatus.Error)
				{
					statusDoc["status"] = "Error";
				}

				context.Response.Write(statusDoc.ToJson());
				
			}
			else
			{
				var fileName = rq.Headers["ufilename"];
				var uploadSlot = UploadManager.Current.GetUploadSlotForFile(fileName);
				System.IO.MemoryStream ms = new System.IO.MemoryStream();
				rq.InputStream.CopyTo(ms);
				uploadSlot.AppendBytes(ms.ToArray());
			}

		}

		public DateTime GetExpiration(string selecteValue)
		{

			return DateTime.UtcNow.AddDays(10);
		}
	}
}